import React from 'react';

import Header from '../common/Header';
import CKModal from '../components/CKModal';
import Validate from '../common/Validate';

import AMUIReact,{
    Container,
    ButtonGroup,
    Button,
    Input,
    Form,
    Icon,
    Selected,
    Grid,
    Col,
    Popover,
    PopoverTrigger,
    UCheck
} from 'amazeui-react';

import Fetch from '../common/Fetch';

import "../assets/css/manage/blog.less";

class BlogEdit extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data:{
                blog_id:'',
                blog_title:'',
                blog_sub_title:'',
                blog_img:'',
                blog_summary:'',
                blog_text:'',
                blog_html:'',
                ctg_name:'',
                ctg_id:'',
                blog_tags:[]
            },
            category:[],
            t_id:null,
            is_upload:false,
            upload_img:'',
            is_save:false,
            type:this.props.params.id ? 'edit':'add'
        };
        this.file = null;
        this.editor = null;
        this.build_work = null;
        this.build_demo_time = null;
        this.build_work_summary = null;
    }

    componentDidMount() {
        this.initEditor();
    }

    initEditor() {
        this.editor = CodeMirror(document.querySelector('#editor'),{
            mode: "markdown",
            theme:'dracula',
            styleActiveLine: true,
            matchBrackets: true,
            lineNumbers: true
        });

        this.editor.on('change',() => {
            clearTimeout(this.build_demo_time);
            this.build_demo_time = setTimeout(()=>{
                this.buildDemo();
                this.buildSummary();
            },1500);
        });

        this.loadCategory();
    }

    buildDemo() {
        if (!this.build_work) {
            this.build_work = new Worker('vendor/works/build_marked.js');
            this.build_work.onmessage = (e)=>{
                $('#markdown_demo').html(e.data);
            };

            this.build_work.onerror = (err)=>{
                $('#markdown_demo').html(err.lineno+':'+err.message);
            };
        }

        this.build_work.postMessage(this.editor.getValue());
    }

    buildSummary() {
        if (!this.build_work_summary) {
            this.build_work_summary = new Worker('vendor/works/build_marked.js');
            this.build_work_summary.onmessage = (e)=>{
                $('#blog_summary').html(e.data);
            };

            this.build_work_summary.onerror = (err)=>{
                $('#blog_summary').html(err.lineno+':'+err.message);
            };
        }
        this.build_work_summary.postMessage(this.editor.doc.getRange({line:0,ch:0},{line:10,ch:0}));
    }

    loadCategory() {
        this._modal.load('正在加载数据...');
        Fetch('/res/blog_category/get_list',{},(res)=>{
            if (res.status) {
                var category = res.data.map((item)=>{
                    return {
                        label:item.ctg_name,
                        value:item.ctg_id
                    };
                });
                this.setState({
                    category:category
                });
                this._modal.closeModal();
                if (this.state.type === 'edit') {
                    this.loadData();
                }
            } else {
                this._modal.alert('提示','加载分类数据出错',()=>{
                    this.context.router.push('/blog_manage');
                    return true;
                });
            }
        },()=>{
            this._modal.closeModal();
        });
    }

    loadData() {
        this._modal.load('正在加载数据...');
        Fetch('/res/blog/get_blog',{id:this.props.params.id},(res)=>{
            if (res.status) {
                var data = this.state.data;
                $.map(data,(item,key)=>{
                    data[key] = res.data[key];
                });
                this.setState({
                    data:data
                });

                this.editor.setValue(res.data.blog_text);
                $('#markdown_demo').html(res.data.blog_html);

                this._modal.closeModal();
            } else {
                this._modal.alert('提示','加载文章数据出错',()=>{
                    this.context.router.push('/blog_manage');
                    return true;
                });
            }
        },()=>{
            this._modal.closeModal();
        });
    }

    save = ()=>{
        var data = this.checkData();
        if (data === false) return;
        if (this.state.is_save) return;
        this.setState({
            is_save:true
        });
        this._modal.load('正在保存数据...');
        Fetch('/res/blog/save',data,(res)=>{
            if (res.status) {
                this._modal.alert('成功','保存博客文章数据成功!',()=>{
                    this.context.router.push('/blog_manage');
                });
            } else {
                this._modal.alert('失败','保存博客文章数据失败!!');
                this.setState({
                    is_save:false
                });
            }
        },()=>{
            this._modal.alert('失败','远程调用失败!!');
            this.setState({
                is_save:false
            });
        });
    };

    checkData() {
        var valid = {
            'blog_title':{role:'*2-100',errmsg:'文章标题为2-100个字符'},
            'ctg_id':{role:'*',errmsg:'请选择一个文章分类'},
            'blog_text':{role:'*',errmsg:'您的文章还没有任何内容！写点什么吧！'}
        };
        var data = this.state.data;
        if (this.state.upload_img !== '') {
            data['upload_file'] = this.state.upload_img;
        }
        this.state.category.forEach((item)=>{
            if (item.value === data.ctg_id) {
                data['ctg_name'] = item.label;
                return false;
            }
        });
        data.blog_text = this.editor.getValue();
        data.blog_html = $('#markdown_demo').html();
        data.blog_summary = $('#blog_summary').html();
        try {
            Validate.inst().checkData(data,valid);
            return data;
        } catch (e) {
            this._modal.alert('错误',e);
            return false;
        }
    }

    changeHandler(field){
        return (e)=>{
            var info = this.state.data;
            info[field] = typeof e == 'object' ? e.target.value : e;
            this.setState({data:info});
        }
    }

    uploadImage = ()=>{
        if (!this.file) {
            var self = this;
            this.file = $('<input type="file"/>');
            this.file.on('change',function(e){
                lrz(this.files[0],{width:640,height:320,quality:.9})
                    .then((rst)=>{
                        $('#head_img').attr('src',rst.base64);
                        self.setState({
                            is_upload:true
                        });
                        Fetch('/res/account_manage/upload_img',
                            {base:rst.base64},
                            (res)=>{
                                if (res.status) {
                                    self.setState({
                                        is_upload:false,
                                        upload_img:res.data
                                    });
                                }
                            }
                        );
                    })
                    .catch((err)=>{
                        RUI.DialogManager.alert(err);
                    }).always(()=>{
                    this.file.value = '';
                });
            });
        }
        this.file.click();
    };

    warpHandler = (e)=>{
        this.editor.setOption('lineWrapping',e.currentTarget.checked);
    };

    render() {
        let data = this.state.data;
        return (
            <div className="content">
                <Header title={this.state.type === 'add' ? "新增博客文章":'修改博客文章'} back/>
                <div className="content_main">
                    <div style={{marginBottom:'20px'}}>
                        <h4 className="title">博客文章信息</h4>
                    </div>
                    <Grid className="fixed-max-width">
                        <Col lg={1}></Col>
                        <Col lg={6} lgOffset={5} style={{textAlign:"right"}}>
                            <Button
                                    amStyle="primary"
                                    onClick={this.save}
                                    disabled={this.state.is_save}>
                                {this.state.is_save?'保存中...':'保存文章'}
                            </Button>
                        </Col>
                    </Grid>
                    <Container className="fixed-max-width">
                        <Grid className="doc-g">
                            <Col lg={8}>
                                <Input label="文章标题"
                                       value={data.blog_title || ''}
                                       placeholder="博客文章标题"
                                       onChange={this.changeHandler('blog_title')}
                                />
                            </Col>
                            <Col lg={4}>
                                <div className="am-form-group">
                                    <label className="am-form-label">文章分类</label>
                                    <Selected className="fixed-select-width"
                                              btnStyle="success"
                                              placeholder="请选择分类"
                                              data={this.state.category}
                                              onChange={this.changeHandler('ctg_id')}
                                              value={data.ctg_id || '1'}/>
                                </div>
                            </Col>
                        </Grid>

                        <Input label="文章副标题"
                               value={data.blog_sub_title || ''}
                               placeholder="文章副标题"
                               onChange={this.changeHandler('blog_sub_title')}
                        />
                        <div className="am-form-group">
                            <label className="am-form-label">文章简介</label>
                            <span> (默认取文章内容10行转为HTML显示，注意不要在前10行放代码块)</span>
                            <div id="blog_summary"
                                 style={{height:"auto"}}
                                 dangerouslySetInnerHTML={{__html:data.blog_summary || ''}}
                                 className="markdown_content markdown-body">
                            </div>
                        </div>
                    </Container>
                    <Grid>
                        <Col sm={6}>
                            <div>
                                <label className="am-form-label">编辑文章内容 (Markdown)</label>
                            </div>
                            <ButtonGroup>
                                <PopoverTrigger
                                    amSize="sm" // 设置 popover 大小
                                    placement="top"
                                    popover={<Popover>加粗</Popover>}>
                                    <Button amSize="xs">
                                        <Icon icon="bold"/>
                                    </Button>
                                </PopoverTrigger>
                                <PopoverTrigger
                                    amSize="sm" // 设置 popover 大小
                                    placement="top"
                                    popover={<Popover>加斜</Popover>}>
                                    <Button amSize="xs">
                                        <Icon icon="italic"/>
                                    </Button>
                                </PopoverTrigger>
                                <PopoverTrigger
                                    amSize="sm" // 设置 popover 大小
                                    placement="top"
                                    popover={<Popover>下划线</Popover>}>
                                    <Button amSize="xs">
                                        <Icon icon="underline"/>
                                    </Button>
                                </PopoverTrigger>
                                <PopoverTrigger
                                    amSize="sm" // 设置 popover 大小
                                    placement="top"
                                    popover={<Popover>图片</Popover>}>
                                    <Button amSize="xs">
                                        <Icon icon="file-image-o"/>
                                    </Button>
                                </PopoverTrigger>
                                
                            </ButtonGroup>
                            <Input type="checkbox" label="自动换行"
                                   labelClassName="am-fr"
                                    onChange={this.warpHandler} inline/>
                            <div id="editor"></div>
                        </Col>
                        <Col sm={6}>
                            <label className="am-form-label">预览</label>
                            <div id="markdown_demo" className="markdown_content markdown-body"></div>
                        </Col>
                    </Grid>
                </div>
                <CKModal ref={(c) => this._modal = c}/>
            </div>
        );
    }
}

BlogEdit.contextTypes = {
    router: React.PropTypes.object
};

export default BlogEdit;